package com.haoshuang.zhouzhoubang.ui.page.message.child.error

import android.os.Bundle
import com.haoshuang.zhouzhoubang.R
import com.haoshuang.zhouzhoubang.databinding.FragmentErrorMessageBinding
import com.haoshuang.zhouzhoubang.model.bean.ErrorMessageBean
import com.haoshuang.zhouzhoubang.ui.dialog.ConfirmDialog
import com.haoshuang.zhouzhoubang.ui.page.message.MessageFragment
import com.haoshuang.zhouzhoubang.ui.page.order.appeal.AppealActivity
import com.haoshuang.zhouzhoubang.ui.page.order.appeal.detail.AppealDetailActivity
import com.haoshuang.zhouzhoubang.ui.page.order.rework.refuse.RefuseReworkActivity
import com.haoshuang.zhouzhoubang.ui.page.order.rework.rework.personal.PersonalReworkActivity
import com.haoshuang.zhouzhoubang.ui.page.order.rework.rework.team.TeamReworkActivity
import com.lxj.xpopup.XPopup
import com.mufeng.libs.base.BaseVMFragment
import com.mufeng.libs.core.setEmptyData
import com.mufeng.libs.core.setOnItemChildClick
import com.mufeng.libs.core.setupData
import com.mufeng.libs.core.setupEmptyData
import com.mufeng.libs.state.observeState
import com.mufeng.libs.utils.callPhone
import com.mufeng.libs.utils.startPage
import com.mufeng.libs.utils.startPageForResult
import com.mufeng.libs.utils.toast
import com.mufeng.libs.utils.view.clickWithTrigger
import com.mufeng.libs.utils.view.vertical

/**
 *  
 */
class ErrorMessageFragment : BaseVMFragment<ErrorMessageViewModel, FragmentErrorMessageBinding>() {

    companion object {
        fun getInstance(): ErrorMessageFragment {
            val fragment = ErrorMessageFragment()
            fragment.arguments = Bundle().apply {

            }
            return fragment
        }
    }

    private val data = arrayListOf<ErrorMessageBean>()
    private val adapter = ErrorMessageAdapter(data)

    private var is_deal = 0

    override fun initView(savedInstanceState: Bundle?) {

        binding.apply{
            tvInProgress.isSelected = true
            tvIsDeal.isSelected = false

            tvInProgress.clickWithTrigger {
                if (is_deal == 0) return@clickWithTrigger
                is_deal = 0
                binding.tvInProgress.isSelected = true
                binding.tvIsDeal.isSelected = false
                binding.refreshLayout.autoRefresh()
            }

            tvIsDeal.clickWithTrigger {
                if (is_deal == 1) return@clickWithTrigger
                is_deal = 1
                binding.tvInProgress.isSelected = false
                binding.tvIsDeal.isSelected = true
                binding.refreshLayout.autoRefresh()
            }

            recyclerView.vertical()
                .adapter = adapter
            adapter.setEmptyData()

            // 同意处罚
            adapter.setOnItemChildClick(id = R.id.tvAgreePunishment) { view, position, item ->
                item?.is_read = 1
                vm.masterSetMessageRead(item?.id, 4)
                // 同意处罚
                if (item?.feedback_type == 1){
                    // 订单投诉的 同意
                    vm.masterAgreeComplaint(item?.id.toString())
                }else {
                    vm.masterAgreePunishment(item?.id.toString())
                }
            }
            // 申诉
            adapter.setOnItemChildClick(id = R.id.tvFeedback) { view, position, item ->
                item?.is_read = 1
                vm.masterSetMessageRead(item?.id, 4)
                // 点击申诉
                val pics = item?.pics?.toMutableList()?.apply { addAll(item.apply_reason_images?.toMutableList()?: mutableListOf()) }?.filter { it.isNotEmpty() }
                AppealActivity.launch(mActivity, item?.order_id, item?.id,item?.feedback_type, item?.content, pics?.joinToString(",").toString())
            }

            // 申诉详情
            adapter.setOnItemChildClick(id = R.id.tvFeedbackDetail) { view, position, item ->
                item?.is_read = 1
                vm.masterSetMessageRead(item?.id, 4)
                // 点击申诉查看申诉详情
                val pics = item?.pics?.toMutableList()?.apply { addAll(item.apply_reason_images?.toMutableList()?: mutableListOf()) }?.filter { it.isNotEmpty() }

                AppealDetailActivity.launch(mActivity, item?.order_id, item?.content, pics?.joinToString(",").toString())
            }

            // 拒绝二次上门
            adapter.setOnItemChildClick(id = R.id.tvRefuse) { view, position, item ->
                item?.is_read = 1
                vm.masterSetMessageRead(item?.id, 4)
                XPopup.Builder(mActivity)
                    .asCustom(
                        ConfirmDialog(
                            context = mActivity,
                            title = "温馨提示",
                            content = "是否与客户协商后，\n不是师傅工作中导致。",
                            cancelStr = "未协商，去协商",
                            confirmStr = "确认，已协商",
                            onCancel = {},
                            onConfirm = {
                                startPageForResult<RefuseReworkActivity>(
                                    "orderId" to item?.order_id.toString(),
                                ) { code, data ->
                                    if (code == 200) {
                                        item?.status = "2"
                                        item?.status_text = "已拒绝"
                                        adapter.notifyItemChanged(position)
                                    }
                                }
                            })
                    )
                    .show()
            }

            // 同意二次上门
            adapter.setOnItemChildClick(id = R.id.tvAgree) { view, position, item ->
                item?.is_read = 1
                vm.masterSetMessageRead(item?.id, 4)
                // 跳转到返工页面
                if (item?.is_team == 0) {
                    startPageForResult<PersonalReworkActivity>("order_id" to item.order_id.toString()) { code, data ->
                        if (code == 200) {
                            item.status = "3"
                            item.status_text = "补贴心意金"
                            adapter.notifyItemChanged(position)
                        } else if (code == 201) {
                            // 创建返工单
                            item.status = "1"
                            item.status_text = "已同意返工"
                            adapter.notifyItemChanged(position)
                        }
                    }
                } else {
                    startPageForResult<TeamReworkActivity>("order_id" to item?.order_id.toString()) { code, data ->
                        if (code == 200) {
                            item?.status = "3"
                            item?.status_text = "补贴心意金"
                            adapter.notifyItemChanged(position)
                        } else if (code == 201) {
                            // 创建返工单
                            item?.status = "1"
                            item?.status_text = "已同意返工"
                            adapter.notifyItemChanged(position)
                        }
                    }
                }
            }

            adapter.setOnItemChildClick(id = R.id.ivCallPhone) { view, position, item ->
                item?.is_read = 1
                vm.masterSetMessageRead(item?.id, 4)
                // 拨打电话
                if (item?.user_phone.isNullOrEmpty()) {
                    toast("电话不能为空")
                }
                mActivity.callPhone(item?.user_phone!!)
            }

            refreshLayout.setOnRefreshListener {
                isShowing = false
                p = 1
                vm.getMasterOrderFeedbackMsg(p, is_deal)
            }

            refreshLayout.setOnLoadMoreListener {
                isShowing = false
                p++
                vm.getMasterOrderFeedbackMsg(p, is_deal)
            }
        }

    }

    override fun initData() {

    }

    override fun lazyLoadData() {

    }

    override fun onResume() {
        super.onResume()
        binding.refreshLayout.autoRefresh()
    }

    override fun startObserve() {

        vm.getMasterOrderFeedbackMsgData.observeState(this) {
            onLoading { showLoading() }
            onError { code, msg ->
                dismissLoading()
                toast(msg)
                binding.refreshLayout.setupEmptyData(data, adapter, p)
            }
            onSuccess {
                dismissLoading()
                binding.refreshLayout.setupData(it?.data, data, adapter, p)
                (parentFragment as MessageFragment).setUnReadButton(3, it?.data?.firstOrNull { it.is_read == 0 } != null)
            }
        }

        // 师傅同意处罚
        vm.masterAgreePunishmentData.observeState(this) {
            onLoading {
                isShowing = true
                showLoading()
            }
            onError { code, msg ->
                dismissLoading()
                toast(msg)
            }
            onSuccess {
                dismissLoading()
                binding.refreshLayout.autoRefresh()
            }
        }
        // 师傅同意处罚  订单投诉
        vm.masterAgreeComplaintData.observeState(this) {
            onLoading {
                isShowing = true
                showLoading()
            }
            onError { code, msg ->
                dismissLoading()
                toast(msg)
            }
            onSuccess {
                dismissLoading()
                binding.refreshLayout.autoRefresh()
            }
        }
    }
    fun setMessageRead() {
        data.forEach {
            it.is_read = 1
            it.isFirstRead = false
        }
        data.firstOrNull()?.isFirstRead = true
        adapter.notifyDataSetChanged()
    }
}